package cn.TcpService;

import java.util.Timer;
import java.util.TimerTask;

import cn.tcp.TcpNewUtil;
import cn.tcpTask.SwitchTask;

public class CoilTask extends TimerTask {

	private static Timer timer;
	private int decid;
	private int switchid;
	private long delay;
	private boolean writeValue;
	private String host;
	private boolean flag = true;
	private CoilSchedule[] cs;
    private int CurrentSwitchid;
	/**
	 * 
	 * @param host
	 *            主机
	 * @param deviceID
	 *            节点ID
	 * @param switchID
	 *            开关通道ID
	 * @param wirteValue
	 *            写入值
	 * @param delay
	 *            多久后开始执行。
	 */
	public CoilTask(String host, int deviceID, int switchID,
			boolean wirteValue, long delay) {
		this.decid = deviceID;
		this.switchid = switchID;
		this.delay = delay;
		this.host = "192.168.1.122";
		this.writeValue = wirteValue;
	}

	public CoilTask(CoilSchedule[] cs) {
		this.cs = cs;
	}

	public boolean startSwitchTask() {
        long delayTime=0;
		try {
			
			for (int i = 0; i < cs.length; i++) {
				//获取执行前的当前时间
				long beforeTime = System.currentTimeMillis();
				CurrentSwitchid=i;
				timer = new Timer(true);
				CoilTask mt = new CoilTask(host, cs[i].getDecid(), cs[i]
						.getSwitchid(), cs[i].isWriteValue(), cs[i].getDelay());
				timer.schedule(mt, delay);  
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void run() {
		TcpNewUtil tnu = new TcpNewUtil();
		tnu.ControlSwitch(decid, switchid, writeValue);
		// 运行完之后 恢复标志位
		flag = false;
	}

	public boolean isFlag() {
		return flag;
	}

}
